import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { userGetInfoService } from '@/api/user.js'

export const useCounterStore = defineStore('counter', () => {
  const articleList = ref([])
  const loading = ref(false)
  const isLoggedIn = ref(!!localStorage.getItem('token'))

  // 获取文章列表
  const getArticleList = async () => {
    console.log('📝 开始获取文章列表...')
    loading.value = true

    try {
      const res = await userGetInfoService()
      console.log('📬 服务器返回数据:', res.data)

      if (res.data.code === 200) {
        articleList.value = res.data.data
        console.log('✅ 文章列表获取成功，数据已存储到 pinia')
        console.log('📋 当前文章列表:', articleList.value)
      } else {
        console.warn('⚠️ 获取文章列表失败:', res.data.message)
      }
    } catch (error) {
      console.error('❌ 获取文章列表出错:', error)
      articleList.value = []
    } finally {
      loading.value = false
    }
  }

  // 设置登录状态
  const setLoginState = (state) => {
    console.log(`🔄 更新登录状态: ${state ? '已登录' : '未登录'}`)
    isLoggedIn.value = state
  }

  // 清除文章列表
  const removeArticleList = () => {
    console.log('🗑️ 清除文章列表数据...')
    articleList.value = []
    setLoginState(false)
    console.log('✅ 文章列表已清空')
  }

  return {
    articleList,
    loading,
    isLoggedIn,
    getArticleList,
    removeArticleList,
    setLoginState
  }
})

// main.js中注册
